package com.wuchao.basedao;

import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

/**
 * @author 吴超66
 * @version 1.0
 * @date 2022/4/11 11:49
 */
public class BaseDao {
    //静态块
    static {
        init();
    }
    private static  String driver;
    private static String url;
    private static String username;
    private static String password;
    public static void init(){
        Properties properties = new Properties();//文件读取对象
        //读文件夹第一时间想到的肯定是io
        InputStream is=BaseDao.class.
                getClassLoader().getResourceAsStream("database.properties");
        try {
            properties.load(is);//加载并读取文件
            driver=properties.getProperty("driver");
            url=properties.getProperty("url");
            username=properties.getProperty("username");
            password=properties.getProperty("password");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    //1 连接
    public Connection getConnection(){
        Connection connection=null;
        try {
            Class.forName(driver);
            connection = DriverManager.getConnection(url, username, password);
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        }return  connection;
    }
    //2关闭
    public  void closeAll(Connection connection, PreparedStatement preparedStatement,
                          ResultSet resultSet){
        try {
            if (connection!=null&!connection.isClosed()){
                connection.close();
            }
            if (preparedStatement!=null&!preparedStatement.isClosed()){
                preparedStatement.close();
            }
            if (resultSet!=null&&!resultSet.isClosed()){
                resultSet.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

    }
}
